import cv2
from cv2 import VideoCapture
from sklearn.svm import SVC
from os import path
import os
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
n_pos = len(os.listdir('target/'))
n_neg = len(os.listdir('error/'))
dataset = [('target/' + f, 1) for f in os.listdir('target/')] + [('error/' + f, 0) for f in os.listdir('error/')]
for i in np.random.choice(os.listdir('target/'), size=(n_neg - n_pos), replace=True):
dataset.append(('target/' + i, 1))
dataset = np.array(dataset)
N = len(dataset)
val_id = np.random.choice(range(N), N // 10, replace=False)
val_set = dataset[val_id]
train_set = dataset[~val_id]
img = cv2.imread('target/00020240.jpg')
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
def feature(image_name):
feat = []
if isinstance(image_name, basestring):
img = cv2.imread(image_name)
else:
img = image_name
feat.append(img.mean(axis=(0, 1)))
for x in np.hsplit(img, 3): # x is (1080, 640, 3)
for y in np.vsplit(x, 3): # y is (360, 640, 3)
feat.append(y.mean(axis=(0, 1)))
return np.array(feat).flatten()
def featurize(dataset):
X = []
y = []
for img, tag in dataset:
try:
X.append(feature(img))
y.append(int(tag))
except:
print img, 'is not an image'
pass
X = np.array(X)
y = np.array(y)
return X, y
X, y = featurize(train_set)
VX, Vy = featurize(val_set)
np.mean(y), np.mean(Vy)
classifier = SVC(probability=True)
classifier.fit(X, y)
predy = classifier.predict(VX)
print 'total accuracy', np.mean(predy == Vy)
print 'false positive', np.mean((Vy == 0) & (predy == 1))
print 'false negative', np.mean((Vy == 1) & (predy == 0))
def video_feature(name):
vid = VideoCapture(name)
frames = []
feat = []
i = 0
while True:
i += 1
if i < 10:
continue
i = 0
ret, img = vid.read()
if not ret:
break
feat.append(feature(img))
frames.append(img)
return np.array(feat), np.array(frames)
TX, frame = video_feature('001e4073d0aaef120fb35e9175370297.mp4')
TX.shape
Ty = classifier.predict(TX)
Ty.sum()
z = []
for i in range(len(TX) - 1):
z.append(np.linalg.norm(TX[i] - TX[i + 1]))
if z[-1] > 50:
print i, z[-1]
plt.imshow(cv2.cvtColor(frame[i], cv2.COLOR_BGR2RGB))
plt.show()
plt.plot(z)
def find_continue_group(ary):
group_start = -1
for a, b in zip(ary[:-1], ary[1:]):
if b - a > 1:
if group_start > 0 and group_len > 1:
print group_start, group_len
group_start = b
group_len = 0
elif b - a == 1 and group_start > 0:
group_len += 1
np.where(np.array(z) > 50)[0]
find_continue_group(np.where(np.array(z) > 50)[0])
for i in range(2517 + 20, 3005 - 20, 100):
plt.imshow(cv2.cvtColor(frame[i], cv2.COLOR_BGR2RGB))
plt.show()
for i in range(1401 + 20, 1573 - 20, 10):
plt.imshow(cv2.cvtColor(frame[i], cv2.COLOR_BGR2RGB))
plt.show()